package com.luoran.system.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.net.HttpHeaders;
import com.luoran.common.core.constant.HttpStatus;
import com.luoran.common.core.utils.SecurityUtils;
import com.luoran.common.core.utils.StringUtils;
import com.luoran.common.core.utils.poi.ExcelUtil;
import com.luoran.common.core.utils.sql.SqlUtil;
import com.luoran.common.core.web.domain.AjaxResult;
import com.luoran.common.core.web.page.PageDomain;
import com.luoran.common.core.web.page.TableDataInfo;
import com.luoran.common.core.web.page.TableSupport;
import com.luoran.common.log.annotation.Log;
import com.luoran.common.log.enums.BusinessType;
import com.luoran.common.security.annotation.PreAuthorize;
import com.luoran.system.domain.SysCar;
import com.luoran.system.domain.SysCarChang;
import com.luoran.system.domain.SysCarType;
import com.luoran.system.domain.dto.EchartsEntity;
import com.luoran.system.service.ISysCarChangService;
import com.luoran.system.service.ISysCarService;
import com.luoran.system.service.ISysCarTypeService;
import com.luoran.system.utils.Result;
import com.luoran.system.utils.TestFileUtil;
import org.apache.http.impl.bootstrap.HttpServer;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

import static com.github.pagehelper.page.PageMethod.startPage;
import static org.apache.http.HttpHeaders.CONTENT_TYPE;

@RestController
@RequestMapping("/car")
public class SysCarController {
    @Autowired
    private ISysCarService sysCarService;
    @Autowired
    private ISysCarChangService iSysCarChangService;
    @Autowired
    private ISysCarTypeService iSysCarTypeService;
    /**
     * 导入车辆信息excel
     */
    @Log(title = "汽车数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysCar> util = new ExcelUtil<>(SysCar.class);
        List<SysCar> trList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = sysCarService.importLogistics(trList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysCar> util = new ExcelUtil<>(SysCar.class);
        util.importTemplateExcel(response,"汽车信息表");
    }
    /**
     * 导出车辆信息excel
     */
    //@PreAuthorize(hasPermi = "system:car:excel")
    @GetMapping("excel")
    public void excelOut(HttpServletResponse response) throws IOException {
        // 获取汽车列表
        SysCar sysCar = new SysCar();
        List<SysCar> list = sysCarService.selectSysCarList(sysCar);

        // 下载 Excel
        download(response, SysCar.class, list);
    }
    public static void download(HttpServletResponse response, Class<SysCar> t, List<SysCar> list) throws IOException {
        response.setContentType(CONTENT_TYPE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + "test.xlsx");

        try {
            EasyExcel.write(response.getOutputStream(), t).sheet("模板").doWrite(list);
        } catch (IOException e) {
            // 记录错误
            throw new RuntimeException("下载 Excel 时发生错误", e);
        }
    }
    private static void setExportHeader(HttpServletResponse response) {
        response.setContentType(CONTENT_TYPE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + "我的数据.xlsx");
    }
    /**
     * 查询车辆信息列表
     */
    @PreAuthorize(hasPermi = "system:car:list")
    @GetMapping("/list")
    public TableDataInfo list(SysCar sysCar){
        startPage();
        System.out.println(sysCar);
        List<SysCar> list = sysCarService.selectSysCarList(sysCar);
        System.out.println(list);
        return getDataTable(list);
    }

    /**
     * 查询厂商信息
     */
    @PreAuthorize(hasPermi = "system:car:listChang")
    @GetMapping("/listChang")
    public List<SysCarChang> listChang(){
        List<SysCarChang> list = iSysCarChangService.selectSysCarChangList();
        return list;
    }

    /**
     * 查询车辆类型方法
     * @return
     */
    @PreAuthorize(hasPermi = "system:car:listType")
    @GetMapping("/listType")
    public List<SysCarType> listType(){
        List<SysCarType> list = iSysCarTypeService.selectSysCarTypeList();
        return list;
    }


    @GetMapping("getListTypeBrand")
    public Result getListTypeBrand() {
        List<EchartsEntity> list = sysCarService.selectTypeBrand();
        return Result.success(list);
    }





    /**
     * 这是汽车信息的添加方法
     * @param sysCar
     * @return
     */
    @PreAuthorize(hasPermi = "system:car:listType")
    @GetMapping("/addCar")
    public boolean addCar(SysCar sysCar){
        boolean b = sysCarService.addCar(sysCar);
        return b;
    }


    @PreAuthorize(hasPermi = "system:car:del")
    @RequestMapping("/del")
    public AjaxResult remove(Long infoIds) {
        System.out.println("前端id===="+infoIds);
        return toAjax(sysCarService.deleteLogininforByIds(infoIds));
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }


    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean result) {
        return result ? success() : error();
    }

    /**
     * 返回成功
     */
    public AjaxResult success() {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error() {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message) {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message) {
        return AjaxResult.error(message);
    }

}
